<template>
  <div id="index" ref="appRef">
    <div class="bg">
      <dv-loading v-if="loading">Loading...</dv-loading>
      <div v-else class="host-body">
        <div class="d-flex jc-center">
          <dv-decoration-10 class="dv-dec-10" />
          <div class="d-flex jc-center">
            <dv-decoration-8 class="dv-dec-8" :color="decorationColors" />
            <div class="title">
              <span class="title-text">平均工作量概览</span>
              <dv-decoration-6
                class="dv-dec-6"
                :reverse="true"
                :color="['#50e3c2', '#67a1e5']"
              />
            </div>
            <dv-decoration-8
              class="dv-dec-8"
              :reverse="true"
              :color="decorationColors"
            />
          </div>
          <dv-decoration-10 class="dv-dec-10-s" />
        </div>

        <!-- 第二行 -->
        <div class="d-flex jc-between px-2">
          <div class="d-flex aside-width">
            <div class="react-left ml-4 react-l-s">
              <span class="react-before"></span>
              <span class="text" @click="goToHomePage">返回首页</span>
            </div>
            <div class="react-left ml-3" style="width: 260px">
              <span class="text">{{ subtitle[1] }}</span>
            </div>
          </div>
          <div class="d-flex aside-width">
            <div
              class="react-right mr-3"
              style="background-color: #0f1325; width: 250px"
            >
              <span class="text fw-b">{{ subtitle[2] }}</span>
            </div>
            <div class="react-right mr-4 react-l-s">
              <span class="react-after"></span>
              <span class="text">
                {{ timeInfo.dateYear }} {{ timeInfo.dateWeek }}
                {{ timeInfo.dateDay }}
              </span>
            </div>
          </div>
        </div>
        <div class="body-box">
          <div class="PerCapitaWorkload">
            <!-- 动态渲染护理类型图表 -->
            <PerCapitaWorkload
              v-for="(type, index) in departmentsOnly"
              :key="index"
              :title="type"
              :PieIndex="index + 1"
              :chart-data="getChartData(type)"
            />
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
  
<script lang="ts">
import { defineComponent, ref, reactive, onMounted, onUnmounted } from "vue";
import { formatTime } from "@/utils/index";
import { WEEK } from "@/constant/index";
import useDraw from "@/utils/useDraw";
import { title, subtitle, moduleInfo } from "@/constant/index";
import { RouterLink, RouterView } from "vue-router";
import PerCapitaWorkload from "../PerCapitaWorkload/PerCapitaWorkloadView.vue";
import axios from "axios"; // 引入axios

export default defineComponent({
  components: {
    PerCapitaWorkload,
  },
  setup() {
    // * 颜色
    const decorationColors = ["#568aea", "#000000"];
    // * 加载标识
    const loading = ref<boolean>(true);
    // * 时间内容
    const timeInfo = reactive({
      setInterval: 0,
      dateDay: "",
      dateYear: "",
      dateWeek: "",
    });
    // * 适配处理
    const { appRef, calcRate, windowDraw, unWindowDraw } = useDraw();

    // 存储接口数据
    const fullStatistics = ref<any[]>([]);
    const departmentsOnly = ref<string[]>([]);

    // 生命周期
    onMounted(() => {
      fetchStatisticsData(); // 调用接口
      handleTime();
      windowDraw();
      calcRate();
    });

    onUnmounted(() => {
      unWindowDraw();
      clearInterval(timeInfo.setInterval);
    });

    // 调用接口获取数据
    const fetchStatisticsData = async () => {
      try {
        const response = await axios.get(
          window.globalConfig.baseApi +"/api/Nurse/GetStatisticsDataJsonByDept?dbKey=dbFY"
        );
        const data = response.data;
        fullStatistics.value = data.fullStatistics || [];
        departmentsOnly.value = data.departmentsOnly || [];
      } catch (error) {
        console.error("获取统计数据失败:", error);
      } finally {
        cancelLoading(); // 无论成功失败都关闭loading
      }
    };

    // 处理图表数据
    const getChartData = (type: string) => {
      // 提取所有科室作为x轴
      const deptNames = [
        ...new Set(
          fullStatistics.value
            .filter((item) => item.iiiDataType === type)
            .map((item) => item.deptName)
        ),
      ];

      // 构建本期数据（number）
      const currentData = deptNames.map((dept) => {
        const item = fullStatistics.value.find(
          (stat) => stat.iiiDataType === type && stat.deptName === dept
        );
        return item ? Number(item.number) : 0;
      });

      // 构建同期数据（lastWeekNum）
      const lastWeekData = deptNames.map((dept) => {
        const item = fullStatistics.value.find(
          (stat) => stat.iiiDataType === type && stat.deptName === dept
        );
        return item ? Number(item.lastWeekNum) : 0;
      });

      console.log("处理后的数据:", {
        xAxisData: deptNames,
        seriesData: [
          /* ... */
        ],
        legendData: ["本期", "同期"],
      });

      return {
        xAxisData: deptNames,
        seriesData: [
          {
            name: "本期",
            type: "bar",
            data: currentData,
            barWidth: "30%",
            barGap: "10%",
          },
          {
            name: "同期",
            type: "bar",
            data: lastWeekData,
            barWidth: "30%",
            barGap: "10%",
          },
        ],
        legendData: ["本期", "同期"],
      };
    };

    // 关闭加载动画
    const cancelLoading = () => {
      setTimeout(() => {
        loading.value = false;
      }, 500);
    };

    // 处理时间显示
    const handleTime = () => {
      timeInfo.setInterval = setInterval(() => {
        const date = new Date();
        timeInfo.dateDay = formatTime(date, "HH: mm: ss");
        timeInfo.dateYear = formatTime(date, "yyyy-MM-dd");
        timeInfo.dateWeek = WEEK[date.getDay()];
      }, 1000);
    };

    return {
      loading,
      timeInfo,
      appRef,
      title,
      subtitle,
      moduleInfo,
      departmentsOnly,
      getChartData,
    };
  },
  methods: {
    goToHomePage() {
      this.$router.push({ name: "Index" });
    },
  },
});
</script>
  
<style lang="scss" scoped>
@import "./Css/PerCapitaWorkload.scss";
</style>